/** Global Variable*********** */
NODEDATA = null;
PRODUCTDATA = null;
downloadList = null;
path = {};
/** ************************** */

Ext.setup({
    onReady: function(){
        LOG("Ext.onReady");
        Ext.getBody().mask('Downloading Update File...', 'x-mask-loading', true);
        document.ontouchmove = function(event){
            event.preventDefault();
        };
        if (navigator.userAgent.match(/iPad/) == null && navigator.userAgent.match(/iPhone|Mobile|UP.Browser|Android|BlackBerry|Windows CE|Nokia|webOS|Opera Mini|SonyEricsson|opera mobi|Windows Phone|IEMobile|POLARIS/) != null) {
			path = new Path("/sdcard/uangel/PubClient/");
			//document.all.index_body.style.backgroundImage = "url('"+ path.pre + "bgi/BG01.png')";
			DownloadListURL = 'http://192.168.2.93/DownloadList.json'
			panelMaker();
			getDownloadList();
        }
        else {
			path = new Path("http://192.168.2.93/webPreview/")
			ProductDataURL ='http://192.168.2.93/webPreview/productData.json';
			NodeDataURL='http://192.168.2.93/webPreview/nodeData.json';
			panelMaker();
			AjaxReadNode() // 다운로드 생략하고 Product,Node Data를 웹으로 접근.
        }
        LOG("Browser Info : " + navigator.userAgent)
    }
})

function Path(prePath){
	this.pre = prePath;
	this.sndPath= prePath.substr(8, (prePath.length));
	this.snd = {};
    this.snd.alert = this.sndPath + "alert/alert.mp3";
    this.snd.nextpage = this.sndPath + "event/nextpage.mp3";
	this.snd.bgm = this.sndPath + "bgm/bg03.mp3"
	this.tpl = prePath + "templete/";
}

function getDownloadList(){
	LOG("DownloadListURL:"+DownloadListURL)
    Ext.Ajax.request({
        url: DownloadListURL ,
        timeout: 1000,
        failure: function(response, options){
            Ext.Msg.confirm("알림", '데이터통신이 원활하지 않습니다.\n 업데이트에 실패 하였습니다. \n프로그램을 종료하시겠습니까?', function(btn){
                if (btn == "yes") {
                    navigator.app.exitApp();
                }
                else {
                    AjaxReadNode()
                }
            })
        },
        success: function(response, options){
            var dataObj = Ext.decode(response.responseText);
            fileDownload(dataObj.download);
        }
    });
}

function countPer(){
    var count = 0;
    return function(){
        return (count += 1)
    }
}

function fileDownload(downloadList){
    var fileTransfer = new FileTransfer();
    var filePer = (100 / downloadList.length);
    var completeNum = countPer();
    var nowCount = 0;
    LOG("FILE INTO "+ path.pre)
    for (var i = 0; i < downloadList.length; i++) {
        fileTransfer.download(
			downloadList[i].url, 
			path.pre + downloadList[i].saveName, 
			function(entry){
            //LOG("DownLoad Path and Filename : [" + entry.fullPath + "]");
            nowCount = (completeNum() * filePer).toFixed(2)
            Ext.getBody().mask(nowCount + "%", 'x-mask-loading', true);
            //entry.remove(function(entry){},function(err){})
            if (nowCount > 99.98) {
                return AjaxReadNode();
            }
        }, function(error){
            XLOG("download error source " + error.source);
            XLOG("download error target " + error.target);
            XLOG("upload error code" + error.code);
        });
    }
}


/*****************************************************
 [nodeData.json] Read and Table Create AND Insert
 *****************************************************/
function AjaxReadNode(){
    Ext.getBody().mask('DB 생성중...', 'x-mask-loading', true);
    DB = window.openDatabase("Database", "0.1", "Pub-Client Demo", 5 * 1024 * 1024);
	LOG("NodeDataURL:"+ NodeDataURL)
    Ext.Ajax.request({
        url: NodeDataURL,
		timeout: 1000,
        failure: function(response, options){
            LOG("nodeData.json Ajax Fail");
        },
        success: function(response, options){
            var dataObj = Ext.decode(response.responseText);
            LOG("nodeData.json Ajax Success");
            NODEDATA = dataObj;
        },
        callback: function(opts, isSuccess, response){
			if (NODEDATA == null) {
				tplStart();
			}
			else {
				createTable();
			}
        }
    });
}

function createTable(){
		DB.transaction(createTB, errorCB, successCreateCB);	
}

function createTB(tx){
    tx.executeSql('DROP TABLE IF EXISTS Client_Version');
    tx.executeSql('CREATE TABLE IF NOT EXISTS Client_Version (version, create_time)');
    LOG("-Create ClientVersion");
    
    tx.executeSql('DROP TABLE IF EXISTS Client_Node');
    tx.executeSql('CREATE TABLE IF NOT EXISTS Client_Node (id, node_id, name, nodeNum,productNum,template,PRIMARY KEY (id))');
    LOG("-Create ClientNODE");
    
    tx.executeSql('DROP TABLE IF EXISTS Client_Product');
    tx.executeSql('CREATE TABLE IF NOT EXISTS Client_Product (id, product_id, name, summary, description, preview, language ,PRIMARY KEY (id) )');
    LOG("-Create Client_Product");
    
    tx.executeSql('DROP TABLE IF EXISTS Client_ChildMap');
    tx.executeSql('CREATE TABLE IF NOT EXISTS Client_ChildMap (id, node_id, child_type, child_id, icon, template ,PRIMARY KEY (id, node_id, child_type, child_id) )');
    LOG("-Create Client_ChildMap");
    
    tx.executeSql('DROP TABLE IF EXISTS Client_ResourceMap');
    tx.executeSql('CREATE TABLE IF NOT EXISTS Client_ResourceMap (id, resource_id, type, parent_type, parent_id, path, PRIMARY KEY (id, resource_id, type, parent_type, parent_id))');
    LOG("-Create Client_ResourceMap");
}

function successCreateCB(){
    LOG("Table Created");
    insertTable();
}

function insertTable(){
    DB.transaction(insertTB, errorCB, successInsertCB);
}

function insertTB(tx){
    /** [Client_Version]********************* */
    var d = new Date();
    tx.executeSql('INSERT INTO Client_Version (version, create_time) VALUES ("' + NODEDATA.version + '","' + d.getDate + d.getTime + '")');
    var nodeLen = NODEDATA.node.length;
    /** [Client_Node]************************ */
    var NODE = NODEDATA.node;
    for (var i = 0; i < nodeLen; i++) {
        tx.executeSql('INSERT INTO Client_Node (id,node_id,name, nodeNum,productNum,template) VALUES' + '(' +
        NODE[i].id +
        ',' +
        NODE[i].node_id +
        ',"' +
        NODE[i].name +
        '","' +
        NODE[i].nodeNum +
        '","' +
        NODE[i].productNum +
        '","' +
        NODE[i].template +
        '")');
        /**** [Client_ResourceMap]************************ */
        for (var j = 0; j < NODE[i].resource.length; j++) {
            tx.executeSql('INSERT INTO Client_ResourceMap (id, resource_id, type, parent_type, parent_id, path) VALUES' + '("' +
            NODE[i].resource[j].id +
            '","' +
            NODE[i].resource[j].resource_id +
            '","' +
            NODE[i].resource[j].type +
            '","' +
            "node" +
            '","' +
            NODE[i].node_id +
            '","' +
            path.pre + NODE[i].resource[j].path +
            '")');
        }
        /**** [Client_ChildMap]************************ */
        for (var q = 0; q < NODE[i].childs.length; q++) {
            tx.executeSql('INSERT INTO Client_ChildMap (id, node_id, child_type, child_id, icon, template ) VALUES' + '("' +
            NODE[i].childs[q].id +
            '","' +
            NODE[i].node_id +
            '","' +
            NODE[i].childs[q].child_type +
            '","' +
            NODE[i].childs[q].child_id +
            '","' +
            path.pre + NODE[i].childs[q].icon +
            '","' +
            NODE[i].childs[q].template +
            '")');
        }
    }
    
}

function errorCB(err){
    LOG("Error processing SQL ERROR CODE:[" + err.code + "]");
}

function successInsertCB(){
    LOG("Insert NODEDATA success!");
    AjaxReadProduct()
}

/***************************************
 [productData.json] Read AND Insert
 ***************************************/
function AjaxReadProduct(){
    Ext.Ajax.request({
        url: ProductDataURL,
		timeout: 1000,
        failure: function(response, options){
            XLOG("productData.json Fail");
        },
        success: function(response, options){
            var dataPRO = Ext.decode(response.responseText);
            PRODUCTDATA = dataPRO;
            LOG("READ PRODUCTDATA complete.");
        },
        callback: function(opts, isSuccess, response){
            if(PRODUCTDATA==null){
				tplStart();	
			}else{
				insertProductTB();
			}
        }
    });
}

function insertProductTB(){
    DB.transaction(insertPD, errorCB, successInsertPD);
}

function insertPD(tx){
    /** [Client_Product]********************* */
    var productLen = PRODUCTDATA.product.length;
    var PRODUCT = PRODUCTDATA.product;
    
    for (var i = 0; i < productLen; i++) {
        tx.executeSql('INSERT INTO Client_Product (id, product_id, name, summary, description, preview, language ) VALUES (' +
        PRODUCT[i].id +
        ',' +
        PRODUCT[i].product_id +
        ',"' +
        PRODUCT[i].name +
        '","' +
        PRODUCT[i].summary +
        '","' +
        PRODUCT[i].description +
        '","' +
        path.pre + PRODUCT[i].preview +
        '","' +
        PRODUCT[i].language +
        '")');
        
        for (var j = 0; j < PRODUCT[i].resource.length; j++) {
            tx.executeSql('INSERT INTO Client_ResourceMap(id, resource_id, type, parent_type, parent_id, path) VALUES' + '("' +
            PRODUCT[i].resource[j].id +
            '","' +
            PRODUCT[i].resource[j].resource_id +
            '","' +
            PRODUCT[i].resource[j].type +
            '","' +
            "product" +
            '","' +
            PRODUCT[i].id +
            '","' +
            path.pre + PRODUCT[i].resource[j].path +
            '")');
        }
    }
}

function errorCB(err){
    LOG("Error processing SQL ERROR CODE:[" + err.code + "]");
}

function successInsertPD(){
    LOG("Insert PRODUCTDATA success!");
    Ext.getBody().unmask();
	tplStart();
}


